package com.logic.rpc;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import com.logic.utils.LogicSrvUtils;
import com.pjc.dao.AccessSrvDao;
import com.pjc.db.MySqlConn;
import com.pjc.model.AccessSrv;
import com.pjc.rpc.AccessRpc;
import com.pjc.thrift.TInnerProto;

/**
 * 逻辑服务器与消息服务器接入类(LogicSrv-MsgSrv)
 * 
 * @author 王畅
 * @since 2015年6月21日
 */
public class AccessRpcUtils {

	private static final ConcurrentHashMap<Integer, AccessRpc> rpcClientMap = new ConcurrentHashMap<Integer, AccessRpc>();

	/**
	 * 广播消息
	 * 
	 * @author 王畅
	 * @param proto
	 * @throws Exception
	 */
	public static void broadcastMsg(TInnerProto proto) throws Exception {
		List<AccessSrv> list = AccessSrvDao.getAccessSrvList(MySqlConn.getInstance().getConn());
		for (AccessSrv srv : list) {
			AccessRpc rpcClient = rpcClientMap.get(srv.getId());
			if (rpcClient == null) {
				rpcClient = newClient(srv);
				rpcClientMap.put(srv.getId(), rpcClient);
			}
			rpcClient.send(proto);
		}
	}

	/**
	 * 实例化客户端对象
	 * 
	 * @author 王畅
	 * @param srv
	 * @return
	 */
	public static AccessRpc newClient(AccessSrv srv) {
		AccessRpc client = new AccessRpc(srv.getHost(), srv.getThriftPort(), 30000, 30, 7);
		return client;
	}

	/**
	 * 发送消息
	 * 
	 * @author 王畅
	 * @param appID
	 * @param srvId
	 * @param proto
	 * @return
	 * @throws Exception
	 */
	public static int sendToAccessSrv(String appID, int srvId, TInnerProto proto) throws Exception {
		proto.setFromSrv(LogicSrvUtils.SERVER_ID);
		AccessRpc rpcClient = (AccessRpc) rpcClientMap.get(Integer.valueOf(srvId));
		if (rpcClient == null) {
			AccessSrv srv = AccessSrvDao.getAccessScr(appID.toLowerCase() + ":access:srv:", srvId);
			rpcClient = newClient(srv);
			rpcClientMap.put(Integer.valueOf(srv.getId()), rpcClient);
		}
		return rpcClient.send(proto);
	}

}
